package com.example.httpclient;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class HttpClientActivity extends Activity {
    private String tag = "HttpClient";

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button button = (Button) findViewById(R.id.btnRequest);
        button.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
		        //URI uri = URI.create("http://www.dcc.ufrj.br/~expedit/lorem.txt");//texto longo
		        URI uri = URI.create("http://www.dcc.ufrj.br/~expedit/mensagem.txt");//texto curto
		        String texto = download(uri);

		        TextView txtView = (TextView) findViewById(R.id.txtResponse);
				txtView.setText(texto.substring(0, Math.min(1000, texto.length())) + "...");
			}
		});
    }

	private String download(URI uri) {
        try {
			HttpClient httpClient = new DefaultHttpClient();
			HttpGet httpGet = new HttpGet(uri);
			HttpResponse response = httpClient.execute(httpGet);
			HttpEntity entity = response.getEntity();
			if (entity != null) {
				InputStream in = entity.getContent();
				String texto = readString(in);
				return texto;
			}
		} catch (ClientProtocolException e) {
			Log.e(tag , e.getMessage());
		} catch (IllegalStateException e) {
			Log.e(tag, e.getMessage());
		} catch (IOException e) {
			Log.e(tag, e.getMessage());
		}
		return "";
	}
	
	private String readString(InputStream in) {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		byte [] buffer = new byte[1024];
		int len = 0;
		
		try {
			while ((len=in.read(buffer)) > 0) {
				bos.write(buffer, 0, len);
				if (bos.size() > 512 * 1024) bos.reset(); 
			}
		} catch (IOException e) {
			Log.e(tag, e.getMessage());
		}
		return new String(bos.toByteArray());
	}
}